<template>
  <div class="pagestyle">
    <list_controller ref="zujianname" :options="state.options" v-if="!state.addModal" :noprintDownShow="true">
      <template v-slot:opraCurdBtnlist="row">
        <span>
          <el-button class="tableFontSize" type="primary" link size="small" @click="editBtn(row.row.row)">编辑</el-button>
          <el-button class="tableFontSize" type="primary" link size="small" @click="deleteBtn(1,row.row.row)">删除
          </el-button>
        </span>
      </template>
      <template v-slot:opraCurdBtnAll>
        <span :class="state.addModal ? 'listInfoBtn active' : 'listInfoBtn'" @click="addBtn">
          <svg-icon :class="state.addModal ? 'active' : ''" class-name="search-icon" icon-class="xinzeng" />
          新增
        </span>
        <span :class="'listInfoBtn'" @click="deleteBtn(0)">
          <svg-icon class-name="search-icon" icon-class="shanchu" />
          删除
        </span>
      </template>
      <template v-slot:selectNamelist> 风机组合关系 </template>
    </list_controller>
    <div class="addBox" v-if="state.addModal">
      <stepcom :stepNum="stepNum" :stepList="stepList"></stepcom>
      <div class="step box_one" v-if="stepNum == 1">
        <div class="item">
          设置闭锁分站风机断电关系
          <el-input v-model="state.formData.name" style="width: 289px;margin:20px 0 0 0;" placeholder="请输入" />
        </div>
        <div class="btnSubmit">
          <el-button type="info" @click="nextStep(9)">取消</el-button>
          <el-button type="primary" @click="nextStep(1)">下一步</el-button>
        </div>
      </div>
      <div v-if="stepNum == 2" class="step">
        <p class="p_title">查询测点</p>
        <div style="background:rgba(91, 109, 128, .04);margin:0 10px;padding: 10px;">
          <querybox :queryList="state.querystwo" @query="queryClick"></querybox>
          <vxe-table height="200" :data="state.listAnalog" border="inner">
            <vxe-column field="pointId" title="测点编号"></vxe-column>
            <vxe-column field="sensorName" title="传感器名称"></vxe-column>
            <vxe-column field="placeName" title="地点"></vxe-column>
            <vxe-column title="操作" :min-width="80">
              <template #default="{ row,rowIndex }">
                <el-button type="text" @click="selectClick(row,rowIndex)">选择</el-button>
              </template>
            </vxe-column>
          </vxe-table>
        </div>
        <p class="p_title">已选因子({{ state.yinziList.length }})</p>
        <yincard :gaojiBtnShow="true" :cardList="state.yinziList" :biaodaList="state.biaodaList" :listAnalog="state.listAnalog"></yincard>
        <div class="btnSubmit">
          <el-button type="info" @click="nextStep(9)">取消</el-button>
          <el-button type="info" @click="nextStep(0)">上一步</el-button>
          <el-button type="primary" @click="nextStep(2)">下一步</el-button>
        </div>
      </div>
      <div v-if="stepNum == 3" class="step">
        <p class="p_title">已选因子({{state.yinziList.length}})</p>
        <div style="background:rgba(91, 109, 128, .04);margin:0 10px;padding: 10px;">
          <vxe-table height="200" :data="state.yinziList" border="inner">
            <vxe-column type="seq" :width="55" title="序号"></vxe-column>
            <vxe-column field="title" title="管道名称"></vxe-column>
            <vxe-column field="place" title="地点"></vxe-column>
            <vxe-column title="断电模式">
              <template #default="{ row }">
                <el-select v-model="row.powerOffMode" placeholder="请选择" style="width: 240px">
                  <el-option v-for="item in cutMod" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </template>
            </vxe-column>
            <vxe-column title="故障断电" :min-width="80">
              <template #default="{ row }">
                <el-switch v-model="row.faultPowerOutage" />
              </template>
            </vxe-column>
            <vxe-column title="操作" :min-width="80">
              <template #default="{ row }">
                <el-button type="text" @click="selectHBClick(row)">选择</el-button>
                <el-button type="text" @click="removeHBClick(row.code)">移除</el-button>
              </template>
            </vxe-column>
          </vxe-table>
        </div>
        <yunsuanfu :yinziList="state.yinziListHB" :biaodaList="state.biaodaList" :gasFuhao="true" @threeStep="threeStep"
          :expression="state.expression">
        </yunsuanfu>
        <div class="remarkBox">
          <p>备注</p>
          <el-input :rows="3" v-model="state.formData.remark" type="textarea" placeholder="请输入">
          </el-input>
        </div>
        <div class="btnSubmit" style="margin:5px 0 0 0;">
          <el-button type="info" @click="nextStep(9)">取消</el-button>
          <el-button type="info" @click="nextStep(1)">上一步</el-button>
          <el-button type="primary" @click="sumbitClick">保存</el-button>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
  import list_controller from "@/components/commonCom/list_controller";
  import {
    computed,
    onMounted,
    reactive
  } from "vue";
  import {
    table_headers
  } from "@/components/commonCom/table_headers";
  import axios from "@/utils/request";
  import {
    arrcompareRemove
  } from "@/utils/arrfun"
  import usePagesStore from "@/store/modules/pages";
  import {
    ElMessage,
    ElMessageBox
  } from "element-plus";
  import stepcom from '../ybjConfig/zuheCom/stepcom.vue'
  import yincard from '../ybjConfig/zuheCom/yincard.vue'
  import yunsuanfu from '../ybjConfig/zuheCom/yunsuanfu.vue'


  const {
    proxy
  } = getCurrentInstance();
  const store = usePagesStore();
  const router = useRouter();
  const upload = ref(null);
  let state = reactive({
    options: {
      tableheads: computed(() => table_headers.configFanAccumulation),
      queryList: {
        dropdownUrl: "",
        querys: [],
        queryMap: new Map([]),
      },
      dataUrl: "/fan/combination/list",
    },
    querystwo: [{
      field: 'pointIds',
      title: '测点编号',
      type: 'input',
      binddata: ''
    }, {
      field: 'placeName',
      title: '安装地点',
      type: 'input',
      binddata: ''
    }],
    listAnalog: [],
    yinziList: [],
    yinziListnewCode: [],
    yinziListHB: [],
    addModal: false,
    open_detail: false,
    formData: {},
    modalTitle: '',
    expression: '',
    biaodaList: [{
      name: '与',
      sub: '&&'
    }, {
      name: '或',
      sub: '||'
    }, {
      name: '左括号',
      sub: '('
    }, {
      name: '右括号',
      sub: ')'
    }, {
      name: '撤',
      sub: '销'
    }, {
      name: '清',
      sub: '空'
    }]
  });
  const stepNum = ref(1)
  const stepList = ref([{
      name: '设置名称',
      code: 1
    },
    {
      name: '选择因子',
      code: 2
    },
    {
      name: '分析条件',
      code: 3
    }
  ])
  const yinziList = ref([])
  const cutMod = ref([{
    label: '开断电',
    value: '开断电'
  }, {
    label: '停断电',
    value: '停断电'
  }])
  // 获取管道列表 
  const getPipeList = () => {
    axios.post('/combination/listSwitch', {
      primaryIndexId: 22
    }).then(res => {
      state.listAnalog= arrcompareRemove(res.data,state.yinziList,'pointId')
    })
  }
  // 获取数据详情 
  const getDataInfo = (obj) => {
    axios.post('/fan/combination/getById', {
      id: obj.id
    }).then(res => {
      state.formData = res.data
      state.expression = state.formData.expression
      state.yinziList = []
      state.yinziListHB = []
      state.formData.pointDtoList.forEach(item => {
        if (item.marker) {
          state.yinziList.push(item)
        } else {
          state.yinziListHB.push(item)
        }
      })
      state.yinziList.forEach(item => {
        item.pointId = item.code
        item.newStation = item.code.substring(0, 3)
        item.title = item.code + '/' + item.name
        item.objarr = [{
            left: '编号',
            right: item.code
          },
          {
            left: '名称',
            right: item.title
          },
          {
            left: '位置',
            right: item.place
          }
        ]
      })
    })
  }


  // 打开新增弹窗 
  const addBtn = () => {
    state.addModal = true
    state.modalTitle = '新增'
    state.yinziList = []
    state.yinziListnewCode = []
    getPipeList()
  }
  // 下一步
  const nextStep = (n) => {
    if (n == 9) {
      close()
    }
    if (n == 0) {
      stepNum.value = 1
    }
    if (n == 1) {
      if (state.formData.name && state.formData.name != '') {
        stepNum.value = 2
      } else {
        ElMessage.error('逻辑名称不能为空')
      }
    } else if (n == 2) {
      if(state.yinziList.length==0){
        stepNum.value = 2
        ElMessage.error('请先选择测点因子')
      }else{
        stepNum.value = 3
      }
    }
  }
  // 根据某字段判断重复
  function hasDifferentElements(arr) {
    return new Set(arr).size > 1;
  }
  // 选择行数据
  const selectClick = (row, index) => {
    row.marker = true
    row.newStation = row.pointId.substring(0, 3)
    row.title = row.pointId + '/' + row.sensorName
    row.code = row.pointId
    row.name = row.sensorName
    row.place = row.placeName
    row.faultPowerOutage = true
    row.objarr = [{
        left: '编号',
        right: row.code
      },
      {
        left: '名称',
        right: row.title
      },
      {
        left: '位置',
        right: row.placeName
      }
    ]
    state.yinziListnewCode.push(row)
    let arr = state.yinziListnewCode.map(item => {
      return item.newStation
    })
    if (state.yinziListnewCode.length > 1) {
      if (!hasDifferentElements(arr)) {
        state.listAnalog.splice(index, 1)
        state.yinziList = state.yinziList.concat(state.yinziListnewCode)
      } else {
        ElMessage.warning('请选择相同分站下的测点编号！')
      }
    } else {
      state.listAnalog.splice(index, 1)
      state.yinziList = state.yinziList.concat(state.yinziListnewCode)
    }
    yinziList.value = state.yinziList
  }
  // 第三步选择行数据
  const selectHBClick = (row) => {
    if (row.powerOffMode) {
      state.yinziListHB.push(row)
      state.yinziListHB = JSON.parse(JSON.stringify(state.yinziListHB));
      state.yinziListHB.forEach(item => {
        item.marker = false
      })
    } else {
      ElMessage.warning('请选择断电模式')
    }
  }
  // 第三步移除数据
  const removeHBClick = (code) => {
    let num
    state.yinziList.forEach((item, index) => {
      if (code == item.code) {
        num = index
      }
    })
    state.yinziList.splice(num, 1)
  }
  const threeStep = (list) => {
    state.formData.expression = list.expression
    state.formData.pointDtoList = []
    state.formData.pointDtoList.push(...state.yinziList)
    state.formData.pointDtoList.push(...state.yinziListHB)
  }
  // 关闭弹窗时执行
  const close = () => {
    state.addModal = false
    state.formData = {}
    stepNum.value = 1
    state.yinziList = []
    state.yinziListHB = []
    state.expression = ''
  }
  // 提交
  const sumbitClick = () => {
    if (state.formData.expression) {
      state.formData.status = "D"
      if (state.modalTitle.includes('新增')) {
        axios.post('/fan/combination/add', state.formData).then(res => {
          if (res.code == 200) {
            ElMessage.success(res.msg)
            close()
            proxy.$refs['zujianname'].getData()
          }
        })
      } else {
        axios.post('/fan/combination/modify', state.formData).then(res => {
          if (res.code == 200) {
            ElMessage.success(res.msg)
            close()
            proxy.$refs['zujianname'].getData()
          }
        })
      }
    } else {
      ElMessage.warning('请填入公式!')
    }
  }
  // 打开删除弹窗
  const deleteBtn = (n, obj) => {
    if (n == 0) {
      let ids = []
      if (store.records.length > 0) {
        ids = store.records.map(item => {
          return item.id
        })
      } else {
        ElMessage.warning('请先勾选所要删除数据!');
      }
      if (ids.length > 0) {
        ElMessageBox.confirm(
          '是否确认删除?', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
          }
        ).then(() => {
          axios.post('/fan/combination/del', ids).then(res => {
            if (res.code == 200) {
              proxy.$refs['zujianname'].getData()
              proxy.$modal.msgSuccess(res.msg);
              store.records = []
            }
          })
        })
      }
    } else {
      ElMessageBox.confirm(
        '是否确认删除?', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(() => {
        axios.post('/fan/combination/del', [obj.id]).then(res => {
          if (res.code == 200) {
            proxy.$refs['zujianname'].getData()
            proxy.$modal.msgSuccess(res.msg);
            store.records = []
            state.open_detail = false
          }
        })
      })
    }
  }
  // 打开编辑弹窗
  const editBtn = (row) => {
    state.addModal = true
    state.modalTitle = '修改'
    getPipeList()
    getDataInfo(row)
  }

  onMounted(() => {

  })
</script>
<style lang="scss" scoped>
  .addBox {
    padding: 42px 0;
    border-radius: 8px;
    background: rgba(255, 255, 255, 0.8);
    height: 99%;

    .step {
      height: calc(100% - 8px);
      overflow: auto;
    }

    .box_one {
      display: flex;
      align-items: center;
      flex-direction: column;
      justify-content: center;

      .item {
        margin-bottom: 46px;
        display: flex;
        flex-direction: column;
      }
    }

    .p_title {
      font-size: 16px;
      font-weight: 700;
      padding: 0 10px;
    }

    .btnSubmit {
      margin-top: 40px;
      text-align: center;
    }

    .remarkBox {
      padding: 10px;
      font-size: 14px;
    }
  }
</style>